var express = require('express');
var router = express.Router();
const phantom = require('phantom');

router.get('/', (req, res, next) => {
    var _ph = null;
    var _page = null;
    phantom.create(['--ignore-ssl-errors=yes']).then(ph => {
        _ph = ph;
        return _ph.createPage();
    }).then(page => {
        _page = page;
        return _page.property('onConsoleMessage', function (msg) {
            console.log(msg);
        });
    }).then(() => {
        console.log('Setting paperSize');
        return _page.setting('paperSize', {format: 'A4', orientation: 'landscape'})
    }).then(() => {
        console.log('paperSize set successfully');
        console.log('Setting viewportSize');
        return _page.setting('viewportSize', {width: 1920, height: 1080});
    }).then(() => {
        console.log('viewportSize set successfully');
        console.log('Setting DPI');
        return _page.setting('dpi', 130)
    }).then(() => {
        console.log('DPI set successfully');
        console.log('Opening report');
        _page.setting('dpi', 130);
        _page.addCookie({
            'name': 'token',
            'value': '8b628f9b4e454a888aa0d7ae22f2d28620170123160323566',
            'domain': '192.168.1.219'
        });
        // _page.property('cookies').then(cookie => {
        //     res.send(cookie)
        // });
        return _page.open('http://192.168.1.219:7070/analysis/xueyetpl');
        // return _page.open('https://www.baidu.com');
    }).then(status => {
        console.log(status);
        console.log('Preparing to render document');
        _page.evaluate(function () {
            return document.getElementById('foo').innerHTML;
        })
        _page.render(`/f/${new Date().valueOf()}.pdf`);
        return _page.property('content')
    }).then((content) => {
        res.send(content)
        console.log('Rendering completed');
        console.log('Phantom process completed successfully');
        _page.close();
        _ph.exit();
    });
});

module.exports = router;